<template>
  <!-- JCSL风险分析 -->
  <div class="sclriskanalysis">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >
        <!-- 左上方菜单 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.sclriskanalysis_delete"
            @click="handleDelete">
            删 除
          </el-button>
          <el-button
            type="warning"
            size="small"
            plain
            icon="el-icon-download"
            @click="handleExportWord">
            导 出 Word
          </el-button>
        </template>

        <!-- 新增活动表单自定义 -->
        <template slot="xzhdForm">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleRiskActivity({}, '', 'ADD')">
            新增活动
          </el-button>
        </template>

        <!-- 活动列表表单自定义 -->
        <template slot="activitiesForm">
          <avue-crud
            :option="activityOption"
            :data="activityData"
            ref="activityCrud"
          >
            <template slot-scope="scope" slot="menu">
              <el-button
                type="warning"
                plain
                size="mini"
                @click="handleRiskActivity(scope.row, scope.index, 'UPDATE')">
                修 改
              </el-button>
              <el-button
                type="danger"
                plain
                size="mini"
                @click="handleDeleteActivity(scope.row, scope.index)">
                删 除
              </el-button>
            </template>
          </avue-crud>
        </template>
      </avue-crud>

      <!-- 弹窗：风险活动信息 -->
      <sclriskactivity
        :riskActivityDialog="riskActivityDialog"
        :activityType="activityType"
        :aIndex="aIndex"
        :selectedActivity="selectedActivity"
        @saveRiskActivity="saveRiskActivity"
        @cancelSaveRiskActivity="cancelSaveRiskActivity"
        @handleCloseRiskActivity="handleCloseRiskActivity"
      >
      </sclriskactivity>
    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getDeptList,
  removeRiskActivity
} from "@/api/saferisk/sclriskanalysis";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import {
  riskActivityColumn,
  sclAnalysisColumn
} from "./constant/sclriskanalysis.js";
import sclriskactivity from "./components/sclriskactivity.vue";

export default {
  components: {
    sclriskactivity
  },
  data() {
    return {
      activityData: [],
      activityOption: {
        calcHeight: 30,
        tip: false,
        searchShow: false,
        border: true,
        index: false,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        selection: false,
        refreshBtn: false,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 150,
        column: riskActivityColumn
      },
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 6,
        searchMenuSpan: 4,
        border: true,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        columnBtn: false,
        addTitle: "风险评估信息",
        column: sclAnalysisColumn
      },
      // 弹窗：风险活动
      riskActivityDialog: false,
      activityType: "",
      aIndex: "",
      selectedActivity: {}
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // SCL风险辨识列表按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.sclriskanalysis_add, false),
        viewBtn: this.vaildData(this.permission.sclriskanalysis_view, false),
        delBtn: this.vaildData(this.permission.sclriskanalysis_delete, false),
        editBtn: this.vaildData(this.permission.sclriskanalysis_edit, false)
      };
    },

    // SCL风险辨识列表选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    this.getDepts();
  },
  methods: {
    // 获取部门列表
    getDepts() {
      var tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;
      getDeptList(tenantId)
        .then(res => {
          let bmColumn = this.findObject(this.option.column, "bm");
          bmColumn.dicData = res.data.data;
        })
        .then(() => {
          this.onLoad(this.page);
        });
    },

    // 导出Word
    handleExportWord() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("是否导出SCL风险点辨识列表?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        window.open(
          `/api/riskIdentification/sclriskanalysis/export?${
            this.website.tokenHeader
          }=${getToken()}&ids=${this.ids}`
        );
      });
    },

    // 新增
    rowSave(row, done) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      delete row.activities;
      delete row.xzhd;
      row.fxsj =
        row.fxsj !== "" && row.fxsj !== undefined
          ? this.formatDate(row.fxsj)
          : "";
      row["sclRiskActivities"] = [];
      this.activityData.forEach(item => {
        var activity = {
          jcxm: item.jcxm,
          jcbz: item.jcbz,
          bdbzyhg: item.bdbzyhg,
          xyaqcs: item.xyaqcs,
          knx: item.knx,
          yzx: item.yzx,
          fxz: item.fxz,
          fxdj: item.fxdj,
          gjcs: item.gjcs
        };
        row.sclRiskActivities.push(activity);
      });
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message.success("操作成功!");
        done();
      });
    },

    // 格式化分析时间
    formatDate(date) {
      var year = date.getFullYear();
      var month = this.getFullNum(date.getMonth() + 1);
      var day = this.getFullNum(date.getDate());
      return year + "-" + month + "-" + day;
    },

    // 补全时间
    getFullNum(num) {
      if (num < 10) {
        return "0" + num;
      }
      return num;
    },

    // 修改
    rowUpdate(row, index, done) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      delete row.activities;
      delete row.xzhd;
      row.fxsj =
        row.fxsj !== "" &&
        row.fxsj !== undefined &&
        typeof row.fxsj !== "string"
          ? this.formatDate(row.fxsj)
          : row.fxsj;
      row["sclRiskActivities"] = [];
      this.activityData.forEach(item => {
        var activity = {
          jcxm: item.jcxm,
          jcbz: item.jcbz,
          bdbzyhg: item.bdbzyhg,
          xyaqcs: item.xyaqcs,
          knx: item.knx,
          yzx: item.yzx,
          fxz: item.fxz,
          fxdj: item.fxdj,
          gjcs: item.gjcs
        };
        if (item.id !== "" && item.id !== undefined) {
          activity["id"] = item.id;
        }
        if (
          item.sclRiskAnalysisId !== "" &&
          item.sclRiskAnalysisId !== undefined
        ) {
          activity["sclRiskAnalysisId"] = item.sclRiskAnalysisId;
        }
        row.sclRiskActivities.push(activity);
      });
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message.success("操作成功!");
        done();
      });
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开查看&编辑&新增弹唱之前
    beforeOpen(done, type) {
      if (type === "add") {
        this.activityData = [];
        this.activityOption.menu = true;
      } else {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          this.activityData =
            res.data.data.sclRiskActivities !== undefined &&
            res.data.data.sclRiskActivities.length !== 0
              ? res.data.data.sclRiskActivities
              : [];
        });
        if (type === "edit") {
          this.activityOption.menu = true;
        } else if (type === "view") {
          this.activityOption.menu = false;
        }
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变事件
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 获取表格数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    // 删除风险活动
    handleDeleteActivity(row, index) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id === "" || row.id === undefined) {
          this.activityData.splice(index, 1);
        } else {
          removeRiskActivity(row.id).then(res => {
            if (res.data.success) {
              this.activityData.splice(index, 1);
              this.$message.success("删除风险活动成功!");
            }
          });
        }
      });
    },

    /**
     * 弹窗：风险活动
     */

    // 新增&更新风险活动信息
    handleRiskActivity(row, index, type) {
      this.riskActivityDialog = true;
      this.activityType = type;
      this.aIndex = index;
      this.selectedActivity = row;
    },

    // 保存风险活动
    saveRiskActivity(insertData) {
      if (this.aIndex === "") {
        this.activityData.push(insertData);
      } else {
        var updateActivity = this.activityData[this.aIndex];
        updateActivity.jcxm = insertData.jcxm;
        updateActivity.jcbz = insertData.jcbz;
        updateActivity.bdbzyhg = insertData.bdbzyhg;
        updateActivity.xyaqcs = insertData.xyaqcs;
        updateActivity.knx = insertData.knx;
        updateActivity.yzx = insertData.yzx;
        updateActivity.fxz = insertData.fxz;
        updateActivity.fxdj = insertData.fxdj;
        updateActivity.gjcs = insertData.gjcs;
      }
      this.cancelSaveRiskActivity();
    },

    // 取消保存风险活动
    cancelSaveRiskActivity() {
      this.riskActivityDialog = false;
      this.activityType = "ADD";
      this.aIndex = "";
      this.selectedActivity = {};
    },

    // 关闭风险活动弹窗
    handleCloseRiskActivity() {
      this.cancelSaveRiskActivity();
    }
  }
};
</script>

<style lang="scss" scpoed>
@import "./styles/sclanalysisscoped.scss";
</style>